package com.topscomm.file.convert.factory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

import com.alibaba.druid.util.StringUtils;
import com.topscomm.center.pojo.FileManageEntity;
import com.topscomm.center.service.impl.FileManageService;
import com.topscomm.core.FileFormatEnum;
import com.topscomm.file.convert.aspose.AsposeFileConvertToHtml;
import com.topscomm.file.util.FileUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;

/**
 * 文件转换任务
 * 
 * @description:
 * @author: donghang
 * @date: 2021年3月15日下午8:16:13
 * @modify:
 */
public class FileConvertTask implements Callable<Boolean> {

	private String filePath;
	private String targetPath;
	private String identifier;

	public FileConvertTask(String filePath, String targetPath, String identifier) {
		this.filePath = filePath;
		this.targetPath = targetPath;
		this.identifier = identifier;
	}

	/**
	 * 线程进行文件转换
	 * 
	 * @description:
	 * @return
	 * @throws Exception
	 * @author: donghang
	 * @date: 2021年3月15日下午8:19:32
	 * @modify:
	 */
	@Override
	public Boolean call() throws Exception {
		FileConvertFactoryService fileConvertFactoryService = (FileConvertFactoryService) SpringUtil
				.getBean("fileConvertFactoryService");
		// 转为图片格式
		String imageCount = "0";
		// 如果excel格式，也转成html
		String mimeType = FileUtil.getMimeType(filePath).toLowerCase();
		if (!FileUtil.matchMimeType(mimeType, FileFormatEnum.EXCEL.mimeType)) {
			imageCount = fileConvertFactoryService.convertFile(identifier, filePath, targetPath, FileFormatEnum.IMAGE);
		}
		if (FileUtil.matchMimeType(mimeType, FileFormatEnum.EXCEL.mimeType)
				|| FileUtil.matchMimeType(mimeType, FileFormatEnum.WORD.mimeType)
				|| FileUtil.matchMimeType(mimeType, FileFormatEnum.PPT.mimeType)
				|| FileUtil.matchMimeType(mimeType, FileFormatEnum.PDF.mimeType)) {
			AsposeFileConvertToHtml.fileToHtml(identifier, filePath, targetPath);
		}
		// 进行数据库更新操作
		FileManageService fileManageService = (FileManageService) SpringUtil.getBean("fileManageService");
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" identifier='{0}' ", this.identifier);
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.isNumber(imageCount)) {
			map.put(FileManageEntity.FieldImagecount, ConvertUtil.convertToInt(imageCount));
			fileManageService.updateByWhere(map, sql.toString());
		}
		return true;
	}

}
